package com.hoshiicloud.user.controller.rbac;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hoshiicloud.UsersLoginVO;
import com.hoshiicloud.auth.vo.TokenUsersVO;
import com.hoshiicloud.common.rpc.Response;
import com.hoshiicloud.user.controller.BaseController;
import com.hoshiicloud.user.entity.company.Member;
import com.hoshiicloud.user.param.rbac.MemberPageParam;
import com.hoshiicloud.user.param.rbac.MemberUpdateParam;
import com.hoshiicloud.user.param.rbac.MemberWithConsumerParam;
import com.hoshiicloud.user.service.rbac.IMemberService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiSort;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

/**
 * 租户会员Controller类
 *
 * @author : yangcheng
 * @date : 2019/5/15 16:12
 * @mail : maiboyc@163.com
 **/
@Slf4j
@RestController
@RequestMapping("/rbac/member")
@Api(value = "租户会员管理", tags = {"租户会员操作接口"}, produces = MediaType.APPLICATION_JSON_VALUE)
@ApiSort(15)
public class MemberController extends BaseController {

    // 租户会员Service
    @Autowired
    private IMemberService memberService;

    /**
     * 根据ID查询租户会员
     *
     * @param id ID
     * @return Response
     */
    @GetMapping("/{id}")
    @ApiOperation(value = "根据ID查询", notes = "根据ID查询租户会员信息", consumes = MediaType.ALL_VALUE)
    public Response get(@PathVariable("id") Long id) {
        return Response.data(memberService.getById(id));
    }

    /**
     * 根据ID组查询租户会员
     *
     * @param ids ID组
     * @return Response
     */
    @GetMapping("/getByIds")
    @ApiOperation(value = "根据ID组查询", notes = "根据ID组查询租户会员信息", consumes = MediaType.ALL_VALUE)
    public Response get(@RequestParam("ids") List<Long> ids) {
        return Response.data(memberService.getByIds(ids));
    }

    /**
     * 根据姓名查询租户会员
     *
     * @param name 姓名
     * @return Response
     */
    @GetMapping("/find/{name}")
    @ApiOperation(value = "根据姓名查询", notes = "根据姓名查询租户会员信息", consumes = MediaType.ALL_VALUE)
    public Response findByName(@PathVariable("name") String name) {
        return Response.data(memberService.memberList(name));
    }


    /**
     * 分页查询租户会员（post请求，以对象接收参数）
     *
     * @param param 查询参数实体
     * @return Response
     */
    @PostMapping("/list")
    @ApiOperation(value = "分页查询", notes = "分页查询租户会员信息", consumes = MediaType.APPLICATION_JSON_VALUE)
    public Response list(@RequestBody MemberPageParam param) {

        try {
            QueryWrapper<Member> queryWrapper = new QueryWrapper<>();
            queryWrapper.lambda()
                    .eq((param.getRealName() != null), Member::getRealName, param.getRealName())
                    .eq((param.getIdCard() != null), Member::getIdCard, param.getIdCard())
                    .eq((param.getNickName() != null), Member::getNickName, param.getNickName());
            IPage<Member> page = new Page<>(Long.parseLong(param.getPageNumber()), Long.parseLong(param.getPageSize()));
            String key = param.toString() + ",Page{pageNumber=" + param.getPageNumber() + ",pageSize=" + param.getPageSize() + "}";
            return Response.data(memberService.getPage(page, queryWrapper, key));
        } catch (Exception e) {
            log.error("分页查询租户信息异常", e);
            return Response.failed("分页查询租户信息异常");
        }
    }

    /**
     * 根据参数查询租户会员（post请求，以对象接收参数）
     *
     * @param param 查询参数实体
     * @return Response
     */
    @PostMapping("/getMembers")
    @ApiOperation(value = "根据参数查询", notes = "根据参数查询租户会员信息", consumes = MediaType.APPLICATION_JSON_VALUE)
    public Response getMembers(@RequestBody Member param) {
        Response result=Response.data(memberService.getMembers(param));
        return result;
    }

    /**
     * 根据WxOpenId查询租户会员
     *
     * @param wxOpenId 微信用户唯一id
     * @return Response
     */
    @GetMapping("/getMemberByWxOpenId")
    @ApiOperation(value = "根据WxOpenId查询", notes = "根据WxOpenId查询租户会员信息", consumes = MediaType.APPLICATION_JSON_VALUE)
    public Response<Member> getMemberByWxOpenId(String wxOpenId) {
        return Response.data(memberService.getMemberByWxOpenId(wxOpenId));
    }

    /**
     * 根据手机号码查询租户会员
     *
     * @param mobile 手机号码
     * @return Response<Member>
     */
    @GetMapping("/getMemberByMobile")
    @ApiOperation(value = "根据手机号码查询", notes = "根据手机号码查询租户会员信息", consumes = MediaType.APPLICATION_JSON_VALUE)
    public Response<Member> getMemberByMobile(Long companyId,String mobile) {
        return Response.data(memberService.getMemberByMobile(companyId,mobile));
    }

    /**
     * 根据openId和手机号码查询
     *
     * @param wxOpenId 微信用户唯一id
     * @param phone    手机号码
     * @return Response<Member>
     */
    @GetMapping("/getMemberByWxOpenIdOrMobile")
    @ApiOperation(value = "根据openId和手机号码查询", notes = "根据openId和手机号码查询租户会员信息", consumes = MediaType.APPLICATION_JSON_VALUE)
    public Response<Member> getMemberByWxOpenIdOrMobile(@RequestParam("wxOpenId") String wxOpenId, @RequestParam("phone") String phone) {
        return Response.data(memberService.getMemberByWxOpenIdOrMobile(wxOpenId, phone));
    }


    /**
     * 新增租户会员
     *
     * @param entity 保存参数实体
     * @return Response
     */
    @PostMapping("/save")
    @ApiOperation(value = "新增租户会员", notes = "新增租户会员信息", consumes = MediaType.APPLICATION_JSON_VALUE)
    public Response<Long> save(@RequestBody @Validated Member entity) {
        return Response.data(memberService.insert(entity));
    }

    /**
     * 修改租户会员
     *
     * @param param 修改参数实体
     * @return Response
     */
    @PutMapping("/update")
    @ApiOperation(value = "修改租户会员", notes = "修改租户会员信息", consumes = MediaType.APPLICATION_JSON_VALUE)
    public Response<Long> updateById(@RequestBody @Validated MemberUpdateParam param) {
        Member entity = new Member();
        BeanUtils.copyProperties(param, entity);
        return Response.data(memberService.update(entity));
    }

    /**
     * 根据ID删除租户会员
     *
     * @param id 用户ID
     * @return Response
     */
    @DeleteMapping("/delete/{id}")
    @ApiOperation(value = "根据ID删除", notes = "根据ID删除租户会员信息", consumes = MediaType.ALL_VALUE)
    public Response deleteById(@PathVariable("id") Long id) {
        return Response.data(memberService.delete(id));
    }

    /**
     * 查询租户会员信息和平台会员信息
     *
     * @param param 查询参数
     * @return Response<Map < String, Object>>
     */
    @PostMapping("/getMemberWithConsumerInfo")
    @ApiOperation(value = "查询租户会员信息和平台会员信息", notes = "查询租户会员信息和平台会员信息", consumes = MediaType.APPLICATION_JSON_VALUE)
    public Response<Map<String, Object>> getMemberWithConsumerInfo(@RequestBody MemberWithConsumerParam param) {
        Response<Map<String, Object>> rs;
        try {
            Map<String, Object> map = JSONObject.parseObject(JSONObject.toJSONString(param), Map.class);
            rs = Response.data(memberService.getMemberWithConsumerInfo(map, param.toString()));
        } catch (Exception e) {
            logger.error("查询租户会员信息和平台会员信息异常" + "[" + e.getMessage() + "]");
            rs = Response.failed("查询租户会员信息和平台会员信息异常");
        }
        return rs;
    }


    @ApiOperation(value = "根据用户名和密码获取系统用户信息", notes = "返回值包括用户的角色与权限")
    @PostMapping("/getStoreLoginDetail")
    public Response<TokenUsersVO> geStoreMemberUserLoginDetail(@RequestBody Map<String,Object> map) {

        return Response.data(memberService.getStoreMemberUserLoginDetail(map));
    }

    @ApiOperation(value = "根据用户名和密码获取系统用户信息", notes = "返回值包括用户的角色与权限")
    @PostMapping("/getPlatformLoginDetail")
    public Response<TokenUsersVO> getPlatformMemberUserLoginDetail(@RequestBody Map<String,Object> map) {

        return Response.data(memberService.getPlatformMemberUserLoginDetail(map));
    }
}
